package br.com.localizagora.driver;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class DecodeH08 extends Thread{

	private SocketChannel socket;
	private String imei;
	private static ByteBuffer buffer;

	public DecodeH08(SocketChannel socket) {
		buffer = ByteBuffer.allocate(80);
		this.socket = socket;

		start();
	}

	@Override
	public void run() {

		try {
			while(socket.isOpen()){
				getData();
				getImei();
				printBuffer();
				buffer.clear();
			}
			
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void getImei() {
		buffer.position(4);
		StringBuilder sb = new StringBuilder();
		for(int i = 0 ; i < 15 ; i++){
			
			sb.append((char)Integer.parseInt(Long.toHexString(buffer.get()),16));
			
		}
		System.out.println("IMEI : " + sb);
		
	}
	private void getDate() {
		buffer.position(4);
		StringBuilder sb = new StringBuilder();
		for(int i = 0 ; i < 15 ; i++){
			
			sb.append((char)Integer.parseInt(Long.toHexString(buffer.get()),16));
			
		}
		System.out.println("IMEI : " + sb);
		
	}


	public void getData() throws InterruptedException{

		try {

			if(socket.isOpen()){
				int num = socket.read(buffer);

				if(num == -1){
					System.out.println("return -1");
					socket.close();
					Thread.interrupted();
				}
			}

		} catch (IOException e) {
			System.out.println("Erro getData");
			e.printStackTrace();
		}

	}
	public void printBuffer(){

		StringBuilder dadosH = new StringBuilder();
		StringBuilder dadosI = new StringBuilder();

		buffer.flip();

		for (byte b : buffer.array()) {

			//dadosH.append("-" +b);
			dadosI.append("." + (char)Integer.parseInt(Integer.toHexString(b),16));
		}
		buffer.flip();
		for (byte b : buffer.array()) {

			dadosH.append("-" +b);
			//dadosI.append("." +Integer.toHexString(b));
		}

		System.out.println( dadosH + "\n" + dadosI);
	}
}
